<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Repository\TokenRepository;
use App\Repository\UserRepository;
use Dingo\Api\Exception\StoreResourceFailedException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class AddressController
 * @package App\Http\Controllers\Api\V1
 */
class AddressController extends Controller
{
    /**
     * @var UserRepository
     */
    public $user;

    /**
     * AddressController constructor.
     * @param $user
     */
    public function __construct(UserRepository $user)
    {
        //使用中间件进行 权限控制
        $this->middleware('primarytoken')->only('createOrUpdateAddress');
        $this->user = $user;
    }

    /**
     * 用户地址的创建和更新
     * @return string
     */
    public function createOrUpdateAddress()
    {
        $name = app('request')->only('name');
        $mobile = app('request')->only('mobile');
        $province = app('request')->only('province');
        $city  = app('request')->only('city');
        $country = app('request')->only('country');
        $detail = app('request')->only('detail');

        $dataArray = array_merge($name, $mobile, $province, $city, $country, $detail);

        $rules = [
            'name' => ['required'],
            'mobile' => ['required', 'regex:/^1[34578][0-9]{9}$/'],
            'province' =>['required'],
            'city' => ['required'],
            'country' => ['required'],
            'detail' => ['required']
        ];

        $message = [
            'name.required' => '名字不能为空',
            'mobile.required' => '手机号不能为空',
            'mobile.regex' => '请输入正确的手机号',
            'province.required' => '省份不能为空',
            'city.required' => '城市不能为空',
            'country.required' => '县不能为空',
            'detail.required' => 'detail不能为空',
        ];
        $validator = app('validator')->make($dataArray, $rules, $message);

        if ($validator->fails()){
            throw new StoreResourceFailedException('以下字段输入错误',$validator->errors());
        }
        //根据token获取用户uid
        //根据UID查询用户是否存在，不存在抛异常
        //获取客户端提交的地址信息
        //根据用户的地址信息判断是否新增和更新地址

        $uid = TokenRepository::getCurrentUid();
        $user = $this->user->getUserById($uid);
        if (!$user){
            throw  new NotFoundHttpException('用户不存在', null, 60000);
        }

        $userAddress = $user->address;
        if (!$userAddress){
            $user->address()->create($dataArray);
        }else{
            $user->address()->update($dataArray);
        }
        return \Response::json(['message' => 'success', 'status_code'=>201], 201);
    }
}
